package com.example.wordmanage;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * Word文档处理工具类
 * 提供各种Word文档操作的辅助方法
 * 
 * @author Generated
 * @version 1.0
 */
public class WordDocumentUtils {
    
    private static final Logger logger = LoggerFactory.getLogger(WordDocumentUtils.class);
    
    /**
     * 私有构造函数，防止实例化工具类
     */
    private WordDocumentUtils() {
        throw new UnsupportedOperationException("工具类不能被实例化");
    }
    
    /**
     * 检查文件是否为有效的Word文档
     * 
     * @param filePath 文件路径
     * @return 如果是有效的Word文档返回true，否则返回false
     */
    public static boolean isValidWordDocument(String filePath) {
        if (filePath == null || filePath.trim().isEmpty()) {
            return false;
        }
        
        try {
            Path path = Paths.get(filePath);
            if (!Files.exists(path) || !Files.isRegularFile(path)) {
                return false;
            }
            
            String fileName = path.getFileName().toString().toLowerCase();
            return fileName.endsWith(".docx");
            
        } catch (Exception e) {
            logger.warn("检查文件有效性时发生异常: {}", e.getMessage());
            return false;
        }
    }
    
    /**
     * 获取文档的基本信息
     * 
     * @param document Word文档对象
     * @return 文档信息字符串
     */
    public static String getDocumentInfo(XWPFDocument document) {
        if (document == null) {
            return "文档为空";
        }
        
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        int paragraphCount = paragraphs.size();
        
        int totalCharacters = 0;
        int nonEmptyParagraphs = 0;
        
        for (XWPFParagraph paragraph : paragraphs) {
            String text = paragraph.getText();
            if (text != null && !text.trim().isEmpty()) {
                nonEmptyParagraphs++;
                totalCharacters += text.length();
            }
        }
        
        return String.format("文档信息 - 总段落数: %d, 非空段落数: %d, 总字符数: %d", 
                           paragraphCount, nonEmptyParagraphs, totalCharacters);
    }
    
    /**
     * 创建备份文件
     * 
     * @param originalFilePath 原始文件路径
     * @return 备份文件路径
     * @throws WordProcessingException 如果备份过程中发生错误
     */
    public static String createBackup(String originalFilePath) throws WordProcessingException {
        try {
            Path originalPath = Paths.get(originalFilePath);
            if (!Files.exists(originalPath)) {
                throw new WordProcessingException("原始文件不存在: " + originalFilePath);
            }
            
            String fileName = originalPath.getFileName().toString();
            String nameWithoutExt = fileName.substring(0, fileName.lastIndexOf('.'));
            String extension = fileName.substring(fileName.lastIndexOf('.'));
            
            String backupFileName = nameWithoutExt + "_backup" + extension;
            Path backupPath = originalPath.getParent().resolve(backupFileName);
            
            Files.copy(originalPath, backupPath);
            
            logger.info("已创建备份文件: {}", backupPath.toAbsolutePath());
            return backupPath.toAbsolutePath().toString();
            
        } catch (Exception e) {
            throw new WordProcessingException("创建备份文件时发生错误: " + e.getMessage(), e);
        }
    }
    
    /**
     * 清理临时文件
     * 
     * @param filePath 要删除的文件路径
     */
    public static void cleanupTempFile(String filePath) {
        if (filePath == null || filePath.trim().isEmpty()) {
            return;
        }
        
        try {
            Path path = Paths.get(filePath);
            if (Files.exists(path)) {
                Files.delete(path);
                logger.debug("已删除临时文件: {}", filePath);
            }
        } catch (Exception e) {
            logger.warn("删除临时文件时发生异常: {}, 文件: {}", e.getMessage(), filePath);
        }
    }
    
    /**
     * 确保目录存在，如果不存在则创建
     * 
     * @param directoryPath 目录路径
     * @throws WordProcessingException 如果创建目录失败
     */
    public static void ensureDirectoryExists(String directoryPath) throws WordProcessingException {
        try {
            Path path = Paths.get(directoryPath);
            if (!Files.exists(path)) {
                Files.createDirectories(path);
                logger.debug("已创建目录: {}", path.toAbsolutePath());
            }
        } catch (Exception e) {
            throw new WordProcessingException("创建目录失败: " + directoryPath, e);
        }
    }
    
    /**
     * 获取文件大小（以KB为单位）
     * 
     * @param filePath 文件路径
     * @return 文件大小（KB），如果文件不存在返回-1
     */
    public static long getFileSizeInKB(String filePath) {
        try {
            Path path = Paths.get(filePath);
            if (Files.exists(path)) {
                long sizeInBytes = Files.size(path);
                return sizeInBytes / 1024;
            }
        } catch (Exception e) {
            logger.warn("获取文件大小时发生异常: {}, 文件: {}", e.getMessage(), filePath);
        }
        return -1;
    }
    
    /**
     * 验证输出目录是否可写
     * 
     * @param outputPath 输出文件路径
     * @return 如果目录可写返回true，否则返回false
     */
    public static boolean isOutputDirectoryWritable(String outputPath) {
        try {
            Path path = Paths.get(outputPath);
            Path parentDir = path.getParent();
            
            if (parentDir == null) {
                return false;
            }
            
            return Files.isWritable(parentDir);
            
        } catch (Exception e) {
            logger.warn("检查输出目录可写性时发生异常: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 比较两个文件的大小并记录日志
     *
     * @param inputFilePath 输入文件路径
     * @param outputFilePath 输出文件路径
     */
    public static void logFileSizeComparison(String inputFilePath, String outputFilePath) {
        try {
            long inputSize = Files.size(Paths.get(inputFilePath));
            long outputSize = Files.size(Paths.get(outputFilePath));

            logger.info("输入文件大小: {} 字节 ({} KB)", inputSize, inputSize / 1024);
            logger.info("输出文件大小: {} 字节 ({} KB)", outputSize, outputSize / 1024);

            if (inputSize > outputSize) {
                long savedBytes = inputSize - outputSize;
                double savedPercentage = (double) savedBytes / inputSize * 100;
                logger.info("文件大小减少: {} 字节 ({:.2f}%)", savedBytes, savedPercentage);
            } else if (outputSize > inputSize) {
                long increasedBytes = outputSize - inputSize;
                double increasedPercentage = (double) increasedBytes / inputSize * 100;
                logger.info("文件大小增加: {} 字节 ({:.2f}%)", increasedBytes, increasedPercentage);
            } else {
                logger.info("文件大小未变化");
            }
        } catch (Exception e) {
            logger.warn("获取文件大小信息时发生错误: {}", e.getMessage());
        }
    }
}
